package cn.cimoc.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author LGZ
 * @date 2021/11/20 19:48
 * <p>
 * spring工具类
 */
@Component
public class SpringUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    /**
     * <p>
     * 获取IOC容器中的bean
     * @author lgz
     * @date 2021/11/21 15:29
     * @param tClass : 需要获取的bean的类型
     * @return : T
     */
    public static <T> T getBean(Class<T> tClass){
        return applicationContext.getBean(tClass);
    }

    /**
     * <p>
     * 获取IOC容器中的bean
     * @author lgz
     * @date 2021/11/21 15:29
     * @param name : 需要获取的bean的名字
     * @param type : 需要获取的bean的类型
     * @return : T
     */
    public static <T> T getBean(String name, Class<T> type) {
        return applicationContext.getBean(name, type);
    }

    /**
     * <p>
     * 获取一次请求的request
     * @author lgz
     * @date 2021/11/21 15:30
     * @return : javax.servlet.http.HttpServletResponse
     */
    public static HttpServletResponse getHttpServletResponse() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
    }

    /**
     * <p>
     * 获取一次请求的response
     * @author lgz
     * @date 2021/11/21 15:30
     * @return : javax.servlet.http.HttpServletRequest
     */
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

}
